﻿using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DLL;
using NursingFormSystem.Model;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace NursingFormSystem
{
    public partial class NewHealetEducation : Form
    {
        public NursingFormSystem.DNNursingService.BNNursingDocsSystem bnService = new NursingFormSystem.DNNursingService.BNNursingDocsSystem();
        public static Tb_User LoginUser;
        public PatientInfoView formParams;
        public string[] UserParam;
        public Tb_User InitLoginUser(string[] UserParam)
        {
            LoginUser = new Tb_User();
            LoginUser.UserId = UserParam[0];
            LoginUser.UserName = UserParam[1];
            LoginUser.DepartmentCode = UserParam[2];
            LoginUser.DepartmentName = UserParam[3];
            LoginUser.JobTitle = UserParam[4];
            LoginUser.PositionTitle = UserParam[5];
            return LoginUser;
        }

        DataRowCollection templateList;
        public NewHealetEducation(string[] userParam, string[] patient)
        {
            InitializeComponent();
            this.UserParam = userParam;
            InitLoginUser(UserParam);
            string SecondSelect = @"SELECT * FROM [BNNursingDocsSystem_Develop].[dbo].[V_YDHL_PATIENT](NOLOCK) where PATIENT_ID ='" + patient[0] + "' and VISIT_ID = '" + patient[1] + "'";
            DataSet ds = SqlHelper.ExecuteDataset(SecondSelect, CommandType.Text);
            if (ds == null || ds.Tables.Count <= 0) return;
            DataTable Patients = ds.Tables[0];
            gridView1.OptionsMenu.EnableColumnMenu = false;
            gridView1.OptionsCustomization.AllowColumnMoving = false;

            // 1男 2女 值可能是数字或者中文或者空
            string Sex = string.Empty;//默认
            if (Patients == null || Patients.Rows.Count <= 0 || Patients.Rows[0]["SEX"] == DBNull.Value || Patients.Rows[0]["SEX"] == null) Sex = string.Empty;
            string data_sex = Patients.Rows[0]["SEX"].ToString().Trim();
            if (string.IsNullOrEmpty(data_sex)) Sex = string.Empty;
            Sex = data_sex;
            if (data_sex.Equals("1")) Sex = "男";
            if (data_sex.Equals("2")) Sex = "女";
            if (Patients == null || Patients.Rows.Count <= 0) return;
            lblAge.Text = Patients.Rows[0]["Age"].ToString().Trim();
            string PatientID = Patients.Rows[0]["PATIENT_ID"].ToString().Trim();
            object obj = Patients.Rows[0]["IN_DATE"];
            string InDate = string.Empty;
            if (obj != DBNull.Value && obj != null && !string.IsNullOrEmpty(obj.ToString()))
                InDate = Convert.ToDateTime(obj).ToString("yyyy-MM-dd");
            string VisitID = Patients.Rows[0]["VISIT_ID"].ToString().Trim();
            labelName.Text = Patients.Rows[0]["PATIENT_NAME"].ToString().Trim();
            labelPatientID.Text = PatientID;
            labelSex.Text = Sex;
            labelVisitID.Text = VisitID;
            labelInDate.Text = InDate;
            labelBed.Text = Patients.Rows[0]["BED_NO"].ToString().Trim();
            string FirstSelect = @"SELECT  *  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduDiseases](NOLOCK) where DepartmentID like '%" + LoginUser.DepartmentCode + "%'";
            DataTable Diseases = SqlHelper.ExecuteDataset(FirstSelect, CommandType.Text).Tables[0];
            string[] TemplateName = new string[Diseases.Rows.Count];
            templateList = Diseases.Rows;
            for (int i = 0; i < templateList.Count; i++)
            {
                TemplateName[i] = Diseases.Rows[i]["TemplateName"].ToString().Trim();
            }

            ComboBoxItemCollection coll = comboBoxTemplateName.Properties.Items;
            coll.BeginUpdate();
            for (int j = 0; j < TemplateName.Length; j++)
            {
                coll.Add(TemplateName[j]);
            }
            coll.EndUpdate();
            comboBoxTemplateName.SelectedIndex = 0;
            Controls.Add(comboBoxTemplateName);
            comboBoxEdit1_TextChanged(null, null);
        }
        
        private void comboBoxEdit1_TextChanged(object sender, EventArgs e)
        {
            string SecondSelect = @"SELECT * FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduDiseases](NOLOCK) where DepartmentID like '%" + LoginUser.DepartmentCode + "%' and TemplateName = '" + comboBoxTemplateName.Text + "'";
            DataTable Diseases = SqlHelper.ExecuteDataset(SecondSelect, CommandType.Text).Tables[0];
            string[] DiseasesName = new string[Diseases.Rows.Count];
            for (int i = 0; i < Diseases.Rows.Count; i++)
            {
                DiseasesName[i] = Diseases.Rows[i]["DiseasesName"].ToString().Trim();
            }
            comboxDiseasesName.Properties.Items.Clear();
            ComboBoxItemCollection coll = comboxDiseasesName.Properties.Items;
            coll.BeginUpdate();
            for (int j = 0; j < DiseasesName.Length; j++)
            {
                coll.Add(DiseasesName[j]);
            }
            coll.EndUpdate();
            comboxDiseasesName.SelectedIndex = 0;
            Controls.Add(comboxDiseasesName);
            comboxDiseasesName_TextChanged(null, null);      //病种都一样，触发不了TextChanged事件，手动触发
        }

        private void comboxDiseasesName_TextChanged(object sender, EventArgs e)
        {
            comboBoxClassName.Properties.Items.Clear();
            comboBoxClassGuid.Properties.Items.Clear();
            string ThirdSelect = @"SELECT  *  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduDiseases](NOLOCK) where DepartmentID like '%" + LoginUser.DepartmentCode + "%' and TemplateName = '" + comboBoxTemplateName.Text + "' and DiseasesName ='" + comboxDiseasesName.Text + "' ";
            string DiseasesGuid = SqlHelper.ExecuteDataset(ThirdSelect, CommandType.Text).Tables[0].Rows[0]["DiseasesGuid"].ToString();
            labelDiseasesGuid.Text = DiseasesGuid;
            string ForthSelect = @"SELECT *  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduClass](NOLOCK) where DiseasesGuid = '" + DiseasesGuid + "' ";
            DataTable EduClass = SqlHelper.ExecuteDataset(ForthSelect, CommandType.Text).Tables[0];
            string[] ClassName = new string[EduClass.Rows.Count];
            string[] ClassGuid = new string[EduClass.Rows.Count];
            for (int i = 0; i < EduClass.Rows.Count; i++)
            {
                ClassName[i] = EduClass.Rows[i]["Class"].ToString().Trim();
                ClassGuid[i] = EduClass.Rows[i]["ClassGuid"].ToString().Trim();
            }
            ComboBoxItemCollection coll = comboBoxClassName.Properties.Items;
            coll.BeginUpdate();
            ComboBoxItemCollection coll2 = comboBoxClassGuid.Properties.Items;
            coll2.BeginUpdate();
            for (int j = 0; j < ClassName.Length; j++)
            {
                coll.Add(ClassName[j]);
                coll2.Add(ClassGuid[j]);
            }
            coll.EndUpdate();
            comboBoxClassName.SelectedIndex = 0;
            Controls.Add(comboBoxClassName);
            comboBoxEdit3_TextChanged(null, null);
        }

        private void comboBoxEdit3_TextChanged(object sender, EventArgs e)
        {
            comboBoxEdit4.Properties.Items.Clear();
            comboBoxProjectGuid.Properties.Items.Clear();
            string ThirdSelect = @"SELECT  *  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduDiseases](NOLOCK) where DepartmentID like '%" + LoginUser.DepartmentCode + "%' and TemplateName = '" + comboBoxTemplateName.Text + "' and DiseasesName ='" + comboxDiseasesName.Text + "' ";
            string DiseasesGuid = SqlHelper.ExecuteDataset(ThirdSelect, CommandType.Text).Tables[0].Rows[0]["DiseasesGuid"].ToString();
            string FifthSelect = @"SELECT *  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduClass](NOLOCK) where DiseasesGuid = '" + DiseasesGuid + "' and Class = '" + comboBoxClassName.Text + "' ";
            DataTable EduClass = SqlHelper.ExecuteDataset(FifthSelect, CommandType.Text).Tables[0];
            string ClassGuid = EduClass.Rows[0]["ClassGuid"].ToString().Trim();
            string SixthSelect = @"SELECT *  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduProject](NOLOCK) where ClassGuid = '" + ClassGuid + "' ORDER BY OrderNum ASC";
            DataTable Project = SqlHelper.ExecuteDataset(SixthSelect, CommandType.Text).Tables[0];
            string[] ProjectName = new string[Project.Rows.Count];
            string[] ProjectGuid = new string[Project.Rows.Count];
            string[] ProjectContent = new string[Project.Rows.Count];
            for (int i = 0; i < Project.Rows.Count; i++)
            {
                ProjectName[i] = Project.Rows[i]["ProjectName"].ToString().Trim();
                ProjectGuid[i] = Project.Rows[i]["ProjectGuid"].ToString().Trim();  //ProjectGuid为内容id
            }
            ComboBoxItemCollection coll = comboBoxEdit4.Properties.Items;
            coll.BeginUpdate();
            ComboBoxItemCollection coll2 = comboBoxProjectGuid.Properties.Items;
            coll2.BeginUpdate();
            for (int j = 0; j < ProjectName.Length; j++)
            {
                coll.Add(ProjectName[j]);
                coll2.Add(ProjectGuid[j]);
            }
            coll.EndUpdate();
            coll2.EndUpdate();
            comboBoxEdit4.SelectedIndex = 0;
            comboBoxProjectGuid.SelectedIndex = 0;
            Controls.Add(comboBoxEdit4);
            Controls.Add(comboBoxProjectGuid);
            string SeventhSelect = @"SELECT ProjectName as '分类' ,ProjectGuid, ClassGuid,id FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduProject](NOLOCK) where ClassGuid = '" + ClassGuid + "'  ORDER BY OrderNum ASC";
            DataTable Grid = SqlHelper.ExecuteDataset(SeventhSelect, CommandType.Text).Tables[0];

            #region 对gridview进行优化
            Grid.Columns.Add("内容", Type.GetType("System.String"));
            Grid.Columns.Add("宣教对象", Type.GetType("System.String"));
            Grid.Columns.Add("宣教方式", Type.GetType("System.String"));
            Grid.Columns.Add("评价", Type.GetType("System.String"));
            Grid.Columns.Add("勾选", Type.GetType("System.Boolean"));
            Grid.Columns["勾选"].SetOrdinal(0);
            Grid.Columns["分类"].SetOrdinal(1);
            Grid.Columns["内容"].SetOrdinal(2);
            Grid.Columns["宣教对象"].SetOrdinal(3);
            Grid.Columns["宣教方式"].SetOrdinal(4);
            Grid.Columns["评价"].SetOrdinal(5);
            Grid.Columns["id"].SetOrdinal(6);
            gridControl1.DataSource = Grid;
            RepositoryItemComboBox PingJia = new RepositoryItemComboBox();
            PingJia.Items.AddRange(new string[] { "非常满意", "满意", "一般", "不满意" });
            gridControl1.RepositoryItems.Add(PingJia);
            RepositoryItemComboBox XuanJiaoDuiXiang = new RepositoryItemComboBox();
            XuanJiaoDuiXiang.Items.AddRange(new string[] { "本人", "家属", "本人和家属" });
            gridControl1.RepositoryItems.Add(XuanJiaoDuiXiang);
            RepositoryItemComboBox XuanJiaoFangShi = new RepositoryItemComboBox();
            XuanJiaoFangShi.Items.AddRange(new string[] { "口头宣教", "书面宣教", "语音宣教", "视频宣教" });
            gridControl1.RepositoryItems.Add(XuanJiaoFangShi);
            gridView1.Columns["宣教对象"].ColumnEdit = XuanJiaoDuiXiang;
            gridView1.Columns["评价"].ColumnEdit = PingJia;
            gridView1.Columns["宣教方式"].ColumnEdit = XuanJiaoFangShi;
            dateEdit1.Properties.VistaEditTime = DefaultBoolean.True;  //加钟
            dateEdit1.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            for (int i = 0; i < ProjectGuid.Length; i++)
            {
                string LastSelect = @"select * FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduContent](NOLOCK)  where ProjectGuid = '" + ProjectGuid[i] + "' order by id desc";
                DataTable LastView = SqlHelper.ExecuteDataset(LastSelect, CommandType.Text).Tables[0];
                if (LastView.Rows.Count > 0)
                {
                    ProjectContent[i] = LastView.Rows[0]["ProjectContent"].ToString();
                    gridView1.SetRowCellValue(i, gridView1.Columns["内容"], ProjectContent[i]);
                }
            }
            gridView1.OptionsCustomization.AllowSort = false;
            gridView1.Columns["分类"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["内容"].OptionsColumn.AllowEdit = false;
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            gridView1.OptionsView.ColumnAutoWidth = false;
            gridView1.BestFitColumns();
            gridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            gridView1.VertScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            gridView1.Columns["ClassGuid"].Visible = false;
            gridView1.Columns["ProjectGuid"].Visible = false;
            gridView1.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;   //是否显示过滤面板
            gridView1.OptionsCustomization.AllowFilter = false;                      //是否允许过滤
            gridView1.Columns["宣教对象"].Width = 100;
            gridView1.Columns["宣教方式"].Width = 80;
            gridView1.Columns["评价"].Width = 60;
            gridView1.Columns["勾选"].Width = 70;
            gridView1.CustomDrawColumnHeader += gvLampConfig_CustomDrawColumnHeader;
            gridView1.Columns[0].Caption = " ";
            gridView1.Columns[6].Visible = false;
            #endregion
        }
        RepositoryItemCheckEdit CheckItem = new RepositoryItemCheckEdit();
        const string gcCheckFieldName = "勾选";

        private void gvLampConfig_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            GridView _view = sender as GridView;
            NursingFormSystem.Draw.DrawHeaderCheckBox(gridView1, CheckItem, gcCheckFieldName, e);
        }

        private void comboBoxEdit4_TextChanged(object sender, EventArgs e)
        {
            string ThirdSelect = @"SELECT * FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduDiseases](NOLOCK) where DepartmentID like '%" + LoginUser.DepartmentCode + "%' and TemplateName = '" + comboBoxTemplateName.Text + "' and DiseasesName ='" + comboxDiseasesName.Text + "' ";
            string DiseasesGuid = SqlHelper.ExecuteDataset(ThirdSelect, CommandType.Text).Tables[0].Rows[0]["DiseasesGuid"].ToString();
            string FifthSelect = @"SELECT * FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduClass](NOLOCK) where DiseasesGuid = '" + DiseasesGuid + "' and Class = '" + comboBoxClassName.Text + "' ";
            DataTable EduClass = SqlHelper.ExecuteDataset(FifthSelect, CommandType.Text).Tables[0];
            string ClassGuid = EduClass.Rows[0]["ClassGuid"].ToString().Trim();
            string SixthSelect = @"SELECT *  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduProject](NOLOCK) where ClassGuid = '" + ClassGuid + "' and ProjectName = '" + comboBoxEdit4.Text + "'";
            string ProjectGuid = SqlHelper.ExecuteDataset(SixthSelect, CommandType.Text).Tables[0].Rows[0]["ProjectGuid"].ToString();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string value = "";
            int Checked = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    Checked++;
                }
            }
            if (Checked == 0)
            {
                XtraMessageBox.Show("没有勾选任何条目");
                return;
            }
            int count = 0;
            string[] ProjectContentID = new string [Checked];
            string[] ProjectGuid = new string[Checked];
            string[] ClassGuid = new string[Checked];
            string[] ProjectName = new string[Checked];
            string[] ProjectContent = new string[Checked];
            string[] EduMethods = new string[Checked];
            string[] Evaluation = new string[Checked];
            string[] EduObj = new string[Checked];
            for (int i = 0, j = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    comboBoxProjectGuid.SelectedIndex = i;
                    comboBoxClassGuid.SelectedIndex = comboBoxClassName.SelectedIndex;
                    ProjectGuid[j] = gridView1.GetDataRow(i)["ProjectGuid"].ToString();
                    ClassGuid[j] = gridView1.GetDataRow(i)["ClassGuid"].ToString();
                    ProjectContent[j] = gridView1.GetDataRow(i)["内容"].ToString();
                    ProjectName[j] = gridView1.GetDataRow(i)["分类"].ToString();
                    EduMethods[j] = gridView1.GetDataRow(i)["宣教方式"].ToString();
                    Evaluation[j] = gridView1.GetDataRow(i)["评价"].ToString();
                    EduObj[j] = gridView1.GetDataRow(i)["宣教对象"].ToString();
                    ProjectContentID[j] = gridView1.GetDataRow(i)["id"].ToString();
                    j++;
                }
            }
            for (int i = 0; i < Checked; i++)
            {
                string TempInsert = @"insert into HealthEduBase
                                         (DepartmentName,DepartmentID,DiseasesName,DiseasesGuid, ProjectName,ProjectGuid,ProjectContent,ClassName,ClassGuid,EduMethods,PatientName,PatientID,EduNurse,EduDate,Evaluation,EvaluationDate,EduNurseID,EduObj,TemplateID,TemplateName,VisitID,ProjectContentID)
                                         VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}' )";
                TempInsert = string.Format(TempInsert, LoginUser.DepartmentName, LoginUser.DepartmentCode, comboxDiseasesName.Text, labelDiseasesGuid.Text, ProjectName[i], ProjectGuid[i], ProjectContent[i], comboBoxClassName.Text, ClassGuid[i], EduMethods[i], labelName.Text, labelPatientID.Text, LoginUser.UserName, dateEdit1.Text, Evaluation[i], dateEdit1.Text, LoginUser.UserId, EduObj[i], comboBoxTemplateName.Text, comboBoxTemplateName.Text, labelVisitID.Text,ProjectContentID[i]);
                SqlHelper.ExecuteNonQuery(CommandType.Text, TempInsert);
                count++;
            }
            DialogResult InsertAsk;
            if (Checked == count)
            {
                InsertAsk = XtraMessageBox.Show(count + "条记录被新增,是否继续新增该患者其他宣教记录？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            }
            else
            {
                InsertAsk = XtraMessageBox.Show(count + "条记录被新增," + (Checked - count) + "条记录存在,无法新增,是否继续新增该患者其他宣教记录？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            }
            if (InsertAsk == DialogResult.Cancel)
            {
                Close();
            }
            DialogResult = DialogResult.OK;
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            string value = "";
            int Checked = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    Checked++;
                }
            }
            if (Checked == 0)
            {
                XtraMessageBox.Show("没有勾选任何条目");
                return;
            }
            string a = comboBoxEdit1.Text;
            string b = comboBoxEdit2.Text;
            string c = comboBoxEdit3.Text;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    gridView1.SetRowCellValue(i, gridView1.Columns["宣教对象"], a);
                    gridView1.SetRowCellValue(i, gridView1.Columns["宣教方式"], b);
                    gridView1.SetRowCellValue(i, gridView1.Columns["评价"], c);
                }
            }
        }

        private void gridControl1_FocusedViewChanged(object sender, DevExpress.XtraGrid.ViewFocusEventArgs e)
        {
            gridView1.RefreshData();
            gridView1.UpdateCurrentRow();
        }

        private void gridControl1_TextChanged(object sender, EventArgs e)
        {
            gridView1.RefreshData();
            gridView1.UpdateCurrentRow();
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {
            Point pt = gridControl1.PointToClient(MousePosition);
            GridHitInfo info = gridView1.CalcHitInfo(pt);
            if (info.Column == null) return;
            if (!info.InRowCell && info.Column.AbsoluteIndex == 0)//Index判断用于哪一列的列头
            {
                string value;
                int Checked = 0;
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    value = gridView1.GetDataRow(i)["勾选"].ToString();
                    if (value == "True")
                    {
                        Checked++;
                    }
                }
                if (Checked == 0)
                {
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        gridView1.SetRowCellValue(i, gridView1.Columns[0], true);
                    }
                }
                else
                {
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        gridView1.SetRowCellValue(i, gridView1.Columns[0], false);
                    }
                }
            }
        }

        private void NewHealetEducation_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < gridView1.Columns.Count; i++)
            {
                gridView1.Columns[i].Width = Convert.ToInt32(gridView1.Columns[i].Width * 1.3);
            }
        }
    }
}